<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData"  v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              日志分类：
              <el-select v-model="queryData.logCategory" placeholder="请选择日志分类" filterable clearable>
                <el-option v-for="item in dictData.logType" :key="item.valueCode" :label="item.valueName" :value="item.valueCode"></el-option>
              </el-select>
            </div>
            <div>日志编号：<el-input placeholder="请输入日志编号" v-model="queryData.logNumber" clearable class="dzy-custom-input"></el-input></div>
            <div>上报人：<el-input placeholder="请输入上报人" v-model="queryData.userName" clearable class="dzy-custom-input"></el-input></div>
            <div>联系方式：<el-input placeholder="上报人联系方式" v-model="queryData.reportPhone" clearable class="dzy-custom-input"></el-input></div>
            <div>上报时间：
              <el-date-picker
                  v-model="queryData.reportTimeLeft"
                  type="datetime"
                  filterable clearable
                  value-format="timestamp"
                  default-time="12:00:00"
                  :picker-options="dataPickerBeforeTodayOptions"
                  placeholder="选择上报时间">
              </el-date-picker>&nbsp;至
              <el-date-picker
                  v-model="queryData.reportTimeRight"
                  type="datetime"
                  filterable clearable
                  value-format="timestamp"
                  default-time="12:00:00"
                  :picker-options="dataPickerBeforeTodayOptions"
                  placeholder="选择上报时间">
              </el-date-picker>
            </div>
            <div><el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button></div>
            <div><el-button @click="clearQuerData" type="primary" icon="el-icon-search">清除查询条件</el-button></div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows"
            v-on:checkSingleRow="checkSingleRow"
            v-on:changeSingleRow="changeSingleRow"
            v-on:deleSingleRow="deleSingleRow">
          </app-table>
          <el-dialog :title="dialogTitle"
                     :visible.sync="dialogFormVisible"
                     close='close'>
            <el-form :model="formData"
                     ref="formData"
                     :rules="rules"
                     label-width="120px"
                     :disabled="showOnly"
                     size="mini">
              <el-form-item label="上报人" prop="userName">
                <el-input v-model="formData.userName" autocomplete="off" placeholder="请输入上报人"></el-input>
              </el-form-item>
              <el-form-item label="上报人电话" prop="reportPhone">
                <el-input v-model="formData.reportPhone" autocomplete="off" placeholder="请输入上报人电话"></el-input>
              </el-form-item>
              <el-form-item label="上报时间" prop="reportTime">
                <el-date-picker
                  v-model="formData.reportTime"
                  type="datetime"
                  value-format="timestamp"
                  default-time="12:00:00"
                  :picker-options="dataPickerBeforeTodayOptions"
                  placeholder="选择上报时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="日志分类" prop="logCategory">
                <el-select filterable v-model="formData.logCategory" placeholder="请选择日志分类">
                  <el-option v-for="item in dictData.logType" :key="item.valueCode" :label="item.valueName" :value="item.valueCode"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="选择经纬度" prop="longitude">
                <el-col :span="6"><el-input v-model="formData.longitude" :disabled="true" placeholder="经度" ></el-input></el-col>
                <el-col :span="1">-</el-col>
                <el-col :span="6"><el-input v-model="formData.latitude" :disabled="true" placeholder="纬度" ></el-input></el-col>
                <el-col :span="3"><el-button type="text" @click="openSimpleMap">从地图选择</el-button></el-col>
              </el-form-item>
              <el-form-item label="发生地点" prop="happenAddress">
                <el-input v-model="formData.happenAddress" autocomplete="off" placeholder="请输入发生地点"></el-input>
              </el-form-item>
              <el-form-item label="事件描述" prop="description">
                <el-input v-model="formData.description" autocomplete="off" placeholder="请输入事件描述"></el-input>
              </el-form-item>
              <el-form-item label="图片" >
                <app-upload ref="appUpload" v-model="formData.pictureArr" ></app-upload>
              </el-form-item>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog :visible.sync="showMap" title="发生地点标记" width="70%" top="8vh" :before-close="mapCancel">
            <edit-map v-if="showMap" @appMapCallback="appMapCallback"></edit-map>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import EditMap from '@/components/EditMap'
import AppUpload from '@/components/AppMultiUpload'
import GridCascader from '@/components/GridCascader'
import {getLastIdByAllId, isCommonDo} from '@/utils/CommonUtil'
import {getUserDeptTree, getUserInfo} from '@/utils/SessionDataUtil'
import {getLogCategory} from '@/data/DictData'
import {
  createFolkLog,
  deleteFolkLog,
  updateFolkLog,
  findFolkLog,
  getFolkLog,
  updateRecommend,
  getRole
} from '@/http/WangGeGuanLiApi'
import { validatePhone } from '@/utils/validate'
import { getAllRegion } from '@/utils/region'
export default {
  data () {
    return {
      pageData: {},
      formData: {},
      treeData: [],
      roldIdData: [],
      queryData: {},
      dialogTitle: '',
      dialogFormVisible: false,
      currentSelectedData: [],
      showOnly: false,
      showMap: false,
      dictData: {},
      deptIdProps: {
        label: 'name',
        value: 'id'
      },
      treeOption: [],
      deptOption: [],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      tableColumns: [
        {prop: 'logNumber', label: '日志编号'},
        {prop: 'description', label: '事件描述'},
        // {prop: 'townshipRecommendation', label: '推荐', formatter: this.formatterRT},
        {prop: 'recommendedStatus', label: '推荐', formatter: this.formatterRT},
        {prop: 'userName', label: '上报人'},
        {prop: 'reportPhone', label: '上报人联系方式'},
        {prop: 'reportTime', label: '上报时间', formatter: this.formatterTime}
      ],
      rules: {
        // allDeptIdArr: [{
        //   required: true,
        //   message: '请选择部门',
        //   trigger: 'blur'
        // }],
        userName: [{
          required: true,
          message: '请输入上报人',
          trigger: 'blur'
        }],
        reportPhone: [{
          required: true,
          validator: validatePhone,
          message: '请输入正确电话',
          trigger: 'blur'
        }],
        reportTime: [{
          required: true,
          message: '请输入上报时间',
          trigger: 'blur'
        }],
        logCategory: [{
          required: true,
          message: '请选择日志分类',
          trigger: 'blur'
        }],
        longitude: [{
          required: true,
          message: '请选择经纬度',
          trigger: 'blur'
        }],
        happenAddress: [{
          required: true,
          message: '请输入发生地',
          trigger: 'blur'
        }],
        description: [{
          required: true,
          message: '请描述事件',
          trigger: 'blur'
        }]
      }
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    EditMap,
    AppUpload,
    GridCascader
  },
  mounted () {
    this.getTableData()
    this.getTreeData()
    this.getDictData()
    // this.getRoleData()
  },
  methods: {
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          if (this.formData) {
            if (!this.beforeSubmit()) {
              return
            }
            if (this.formData.pictureArr) {
              this.formData.picture = this.formData.pictureArr.length === 0 ? '' : this.formData.pictureArr.join(',')
            }
            if (this.formData.allDeptIdArr && this.formData.allDeptIdArr.length > 0) {
              let len = this.formData.allDeptIdArr.length - 1
              let deptData = {}
              deptData.id = this.formData.allDeptIdArr[len]
              deptData.items = this.deptOption
              deptData.isGetAllId = true
              this.formData.allDeptId = getAllRegion(deptData)
            }
            if (this.formData.id) {
              updateFolkLog(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.cancel(formName)
                  this.$message({
                    type: 'success',
                    message: '修改成功'
                  })
                }
              })
            } else {
              createFolkLog(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.cancel(formName)
                  this.$refs[formName].resetFields()
                  this.$message({
                    type: 'success',
                    message: '新增成功'
                  })
                }
              })
            }
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteFolkLog(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
              }
            })
          })
        })
      }
    },
    beforeSubmit () {
      if (this.formData.allDeptIdArr) {
        if (this.formData.allDeptIdArr && this.formData.allDeptIdArr.length !== 0) {
          let liveIndex = this.formData.allDeptIdArr.length - 1
          let liveData = {}
          liveData.id = this.formData.allDeptIdArr[liveIndex]
          liveData.items = this.treeData
          liveData.isGetAllId = true
          this.formData.allDeptId = getAllRegion(liveData)
        } else {
          this.formData.allDeptId = ''
        }
        this.formData.deptId = getLastIdByAllId(this.formData.allDeptId)
      }
      return true
    },
    cancel (formName) {
      this.dialogFormVisible = false
      this.showMap = false
      this.formData = {}
      this.$refs[formName].resetFields()
      this.$refs.appUpload.clearFileList()
    },
    close () {
      this.dialogFormVisible = false
      this.showMap = false
      this.formData = {}
      this.$refs['formData'].resetFields()
      this.$refs.appUpload.clearFileList()
    },
    getTableData () {
      let param = this.queryData
      findFolkLog(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            isCommonDo(this.pageData, this)
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        }
      })
    },
    getRoleData () {
      getRole().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          console.log(data)
          this.roldIdData = data
        }
      })
    },
    handleCurrentChange (data) {
      this.queryData = {}
      this.queryData.offset = (data - 1) * 10
      this.getTableData()
    },
    getTreeData () {
      this.treeData = getUserDeptTree()
      this.deptOption = getUserDeptTree()
    },
    treeClickHandle (data) {
      this.queryData = {}
      this.queryData.deptId = data.id
      this.getTableData()
      // let allDeptId = getCaseAllGridIdByGridTreeData(data)
      // console.log(data, allDeptId)
      // this.$set(this.formData, 'allDeptIdArr', allDeptId.split(','))
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.treeData
      let gridIdArr = getAllRegion(gridData)
      this.$set(this.formData, 'allDeptIdArr', gridIdArr)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
        // 乡镇推荐
      } else if (callbackData.btnType === 'town_recommend') {
        this.formData = callbackData.rows[0]
        this.formData.recommendedStatus = 2
        updateRecommend(this.formData).then(resp => {
          if (resp.code && resp.code === '200') {
            this.$message({
              type: 'success',
              message: '已设为乡镇推荐'
            })
            this.getTableData()
          }
        })
        // 社区村推荐
      } else if (callbackData.btnType === 'recommend') {
        this.formData = callbackData.rows[0]
        this.formData.recommendedStatus = 1
        updateRecommend(this.formData).then(resp => {
          if (resp.code && resp.code === '200') {
            this.$message({
              type: 'success',
              message: '已设为社区村推荐'
            })
            this.getTableData()
          }
        })
      } else {
        if (callbackData.btnType === 'post') {
          let userInfo = getUserInfo()
          this.$set(this.formData, 'userName', userInfo.name)
          this.$set(this.formData, 'userId', userInfo.id)
          this.$set(this.formData, 'reportPhone', userInfo.phone)
        } else {
          this.formData = callbackData.rows[0]
          getFolkLog(this.formData.id).then(resp => {
            if (resp.code && resp.code === '200') {
              let data = JSON.stringify(resp.data)
              this.formData = JSON.parse(data)
              let deptData = {}
              deptData.id = this.formData.deptId
              deptData.items = this.deptOption
              let deptIdArr = getAllRegion(deptData)
              this.$set(this.formData, 'allDeptIdArr', deptIdArr)
              this.formData.pictureArr = this.toArray(this.formData.picture)
            }
          })
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    toArray (string) {
      let arr = []
      if (string) {
        let stringArr = string.split(',')
        for (let i = 0; i < stringArr.length; i++) {
          let obj = {}
          obj.name = 'IMG_' + i
          obj.url = stringArr[i]
          arr.push(obj)
        }
        return string.split(',')
      } else {
        return []
      }
    },
    checkSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    changeSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    deleSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
      } else {
        this.currentSelectedData = []
      }
    },
    // 检索按钮操作
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.lnglat) {
        this.formData.longitude = appMapInfo.lnglat.lng
        this.formData.latitude = appMapInfo.lnglat.lat
        this.showOnly = false
        this.showMap = false
      }
    },
    openSimpleMap () {
      this.showMap = true
    },
    mapCancel () {
      this.showMap = false
    },
    getDictData () {
      this.dictData.logType = getLogCategory()
    },
    formatterTime (row, column) {
      if (row && row.reportTime) {
        let time = row.reportTime
        return this.$moment(time).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    formatterRT (row, column) {
      if (row) {
        // 0:未推荐;1:村推荐;2:乡镇推荐
        return row.recommendedStatus === 0 ? '未推荐' : (row.recommendedStatus === 1 ? '村推荐' : '乡镇推荐')
      }
    },
    clearQuerData () {
      this.queryData = {}
    }
  }
}
</script>
<style scoped>
 .dzy-custom-search-box>div {
   margin-right: 10px
 }
 .el-form >>> .el-form-item__error {
  margin-top: 2px;
}
.el-form >>> .el-input__inner {
  height: 37px;
}
.el-form >>> .el-form-item__label {
  line-height: 37px;
}
.el-form >>> .el-cascader__label {
  line-height: 37px;
}
</style>
